package com.tuishan.myapplication.Views.Login;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.tuishan.myapplication.Base.BaseContest;
import com.tuishan.myapplication.Custom.LoadingView;
import com.tuishan.myapplication.Eum_Model.EyeEum;
import com.tuishan.myapplication.MainActivity;
import com.tuishan.myapplication.Model.RegisterModel;
import com.tuishan.myapplication.Model.UserModel;
import com.tuishan.myapplication.MyApplication;
import com.tuishan.myapplication.R;
import com.tuishan.myapplication.Servers.BaseCallback;
import com.tuishan.myapplication.Servers.OkHttpHelper;
import com.tuishan.myapplication.Servers.UrlRouter;
import com.tuishan.myapplication.Views.SetActivity;

import java.util.WeakHashMap;

import okhttp3.Request;
import okhttp3.Response;

public class LoginActivity extends Activity implements OnTitleBarListener, View.OnClickListener {
    ImageView eye_btn;
    EditText login_ps_edt;
    EditText phone_edit;
    EditText code_edit;
    EyeEum eyeEum = EyeEum.Close;
    Button code_send_btn;
    Button login_btn;
    TitleBar titleBar;
    private static long TOTAL_TIME = 60000;
    private final static long ONECE_TIME = 1000;
    Context mContext;
    LoadingView Loading;
    MyApplication myApp;
    CheckBox Click_PassWord,Click_Email;
    LinearLayout login_email_line,login_pass_line;
    TextView changePassword_btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mContext = this;
        myApp=(MyApplication)getApplication();
        initView();
        EyeSet(eyeEum);
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString(BaseContest.UserToken,null))) {
            GetUserInfo();
        }
    }

    private void  GetUserInfo(){
        OkHttpHelper mHttpHelper = OkHttpHelper.getInstance();
        mHttpHelper.get(UrlRouter.UserInfo, UserModel.class, new BaseCallback<UserModel>() {
            @Override
            public void onFailure(Request request, Exception e) {

            }
            @Override
            public void onSuccess(Response response, UserModel o) {
                finish();
                Intent intent = new Intent(mContext, MainActivity.class);
                startActivity(intent);
                myApp.setLogin(true);
            }

            @Override
            public void onFalse(Response response, String err_msg) {

            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        });
    }


    private void initView() {
        eye_btn = findViewById(R.id.eye_btn);
        login_email_line = findViewById(R.id.login_email_line);
        login_pass_line = findViewById(R.id.login_pass_line);
        Click_PassWord = findViewById(R.id.Click_PassWord);
        changePassword_btn = findViewById(R.id.changePassword_btn);
        Click_Email = findViewById(R.id.Click_Email);
        eye_btn.setOnClickListener(this);
        login_ps_edt = findViewById(R.id.login_ps_edt);
        code_send_btn = findViewById(R.id.code_send_btn);
        code_send_btn.setOnClickListener(this);
        login_btn = findViewById(R.id.login_btn);
        login_btn.setOnClickListener(this);
        phone_edit = findViewById(R.id.phone_edit);
        code_edit = findViewById(R.id.code_edit);
        titleBar = findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(this);
        Click_PassWord.setOnClickListener(this);
        Click_Email.setOnClickListener(this);
        changePassword_btn.setOnClickListener(this);
        Loading = new LoadingView(mContext);
    }
    /**
     * 关闭或者显示密码
     *
     * @param arg1 开关类型
     */
    private void EyeSet(EyeEum arg1) {
        switch (arg1) {
            case Open:
                eye_btn.setImageDrawable(getResources().getDrawable(R.drawable.visible_icon));
                login_ps_edt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                login_ps_edt.setSelection(login_ps_edt.getText().length());
                eyeEum = EyeEum.Close;
                break;
            case Close:
                eye_btn.setImageDrawable(getResources().getDrawable(R.drawable.invisible));
                login_ps_edt.setTransformationMethod(PasswordTransformationMethod.getInstance());
                login_ps_edt.setSelection(login_ps_edt.getText().length());
                eyeEum = EyeEum.Open;
                break;
        }
    }

    @Override
    public void onLeftClick(View v) {
        Intent intents = new Intent(mContext, SetActivity.class);
        startActivity(intents);
    }

    @Override
    public void onTitleClick(View v) {

    }

    @Override
    public void onRightClick(View v) {
        finish();
        Intent intent = new Intent(this, RegisterActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public void onClick(View view) {
            switch (view.getId()){
                case R.id.changePassword_btn:
                    Intent intent = new Intent(this, ResetPassWordActivity.class);
                    startActivity(intent);
                    break;
                case R.id.eye_btn:
                    EyeSet(eyeEum);
                    break;
                case R.id.code_send_btn:
                    if (!RegexUtils.isEmail(phone_edit.getText().toString().trim())) {
                        Toast.makeText(this, "请确认账号输入是否正确", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    code_send_btn.setEnabled(false);
                    countDownTimer.start();
                    SendCode(phone_edit.getText().toString().trim());
                    break;
                case R.id.login_btn:
                    LoginBtn(phone_edit.getText().toString().trim(), login_ps_edt.getText().toString().trim(), code_edit.getText().toString().trim());
                    break;
                case R.id.Click_PassWord:
                    //login_email_line,login_pass_line;
                    if (Click_PassWord.isChecked()) {
                        Click_Email.setChecked(false);
                        login_email_line.setVisibility(View.GONE);
                    }
                    login_pass_line.setVisibility(View.VISIBLE);
                    break;
                case R.id.Click_Email:
                    if (Click_Email.isChecked()) {
                        Click_PassWord.setChecked(false);
                        login_pass_line.setVisibility(View.GONE);
                    }
                    login_email_line.setVisibility(View.VISIBLE);

                    break;

            }
    }

    /**
     * 时间定时器
     */
    private CountDownTimer countDownTimer = new CountDownTimer(TOTAL_TIME, ONECE_TIME) {
        @Override
        public void onTick(long millisUntilFinished) {
            String value = String.valueOf((int) (millisUntilFinished / 1000));
            code_send_btn.setText(value);
        }

        @Override
        public void onFinish() {
            code_send_btn.setText(getResources().getString(R.string.phone_code));
            code_send_btn.setEnabled(true);
        }
    };

    /**
     * 用户登录
     */
    private void LoginBtn(String email, String Password, String Code) {
        if (!RegexUtils.isEmail(phone_edit.getText().toString().trim())) {
            Toast.makeText(this, "请确认账号输入是否正确", Toast.LENGTH_SHORT).show();
            return;
        }
        Loading.show();
        WeakHashMap<String, Object> objectMap = new WeakHashMap<>();
        objectMap.put("userType", 1);
        objectMap.put("email", email);
        objectMap.put("loginPass", Password);
        objectMap.put("emailCode", Code);
        OkHttpHelper mHttpHelper = OkHttpHelper.getInstance();
        mHttpHelper.post(UrlRouter.LoginUrl, RegisterModel.class, objectMap, new BaseCallback<RegisterModel>() {
            @Override
            public void onFailure(Request request, Exception e) {
                Loading.dismiss();
            }

            @Override
            public void onSuccess(Response response, RegisterModel registerModel) {
                Loading.dismiss();
                Toast.makeText(mContext, "登录成功", Toast.LENGTH_SHORT).show();
                SPUtils.getInstance().put(BaseContest.UserToken, registerModel.getToken());
                myApp.setLogin(true);
                finish();
                Intent intent = new Intent(mContext, MainActivity.class);
                startActivity(intent);
            }
            @Override
            public void onFalse(Response response, String err_msg) {
                Loading.dismiss();
                Toast.makeText(mContext, err_msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {
                Loading.dismiss();
            }
        });
    }


    /**
     * 发送验证码
     */
    private void SendCode(String email) {
        Loading.show();
        WeakHashMap<String, Object> objectMap = new WeakHashMap<>();
        objectMap.put("email", email);
        objectMap.put("typeCode", 3);
        OkHttpHelper mHttpHelper = OkHttpHelper.getInstance();
        mHttpHelper.post(UrlRouter.SendEmail, String.class, objectMap, new BaseCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                Loading.dismiss();
            }

            @Override
            public void onSuccess(Response response, Object o) {
                Toast.makeText(mContext, "验证码发送成功", Toast.LENGTH_SHORT).show();
                Loading.dismiss();
            }

            @Override
            public void onFalse(Response response, String err_msg) {
                Toast.makeText(mContext, "接口失败", Toast.LENGTH_SHORT).show();
                Loading.dismiss();
            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {
                Toast.makeText(mContext, "验证码发送失败", Toast.LENGTH_SHORT).show();
                Loading.dismiss();
            }
        });
    }
}
